package iscas.order.filter;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class TraceRequestInterceptor implements RequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(TraceRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        // Log request details
        logger.info("Feign request to [{}]", template.url());
        // Optionally add or propagate headers
        template.header("X-My-Header", "headerValue");

        // Assuming you are using Slf4j MDC or similar for tracing
        propagateTracingHeaders(template, "X-B3-TraceId", "X-B3-SpanId");
    }

    private void propagateTracingHeaders(RequestTemplate template, String... headers) {
        for (String header : headers) {
            String value = MDC.get(header);
            if (value != null) {
                template.header(header, value);
                logger.info("Propagating header [{}] with value [{}]", header, value);
            }
        }
    }
}
